import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout, QPushButton, 
                            QTabWidget, QScrollArea, QVBoxLayout, QLineEdit)
from PyQt5.QtCore import Qt, pyqtSignal

class LatexKeyboard(QWidget):
    insertSymbol = pyqtSignal(str)  # 符号插入信号

    def __init__(self):
        super().__init__()
        self.setWindowTitle("LaTeX 数学符号键盘")
        self.setFixedSize(800, 400)
        self.init_ui()

    def init_ui(self):
        main_layout = QVBoxLayout()
        tab_widget = QTabWidget()

        # 创建不同分类的符号页
        tab_widget.addTab(self.create_greek_tab(), "希腊字母(小)")
        tab_widget.addTab(self.create_big_greek_tab(),"希腊字母(大)")
        tab_widget.addTab(self.create_operators_tab(), "运算符")
        tab_widget.addTab(self.create_arrows_tab(), "箭头")
        tab_widget.addTab(self.create_sets_tab(), "集合符号")
        tab_widget.addTab(self.create_matrix_tab(), "矩阵")


        main_layout.addWidget(tab_widget)
        self.setLayout(main_layout)

    def create_matrix_tab(self):
        symbols = [
            {"display": "普通矩阵", "code": self.matrix_code("matrix")},
            {"display": "[矩阵]", "code": self.matrix_code("bmatrix")},
            {"display": "(矩阵)", "code": self.matrix_code("pmatrix")},
            {"display": "{矩阵}", "code": self.matrix_code("Bmatrix")},
            {"display": "|矩阵|", "code": self.matrix_code("vmatrix")},
            {"display": "‖矩阵‖", "code": self.matrix_code("Vmatrix")},
            {"display": "⋮", "code": r"\vdots"}, 
            {"display": "⋯", "code": r"\cdots"},
            {"display": "⋱", "code": r"\ddots"},
            {"display": "分块线", "code": r"\hline"},
            {"display": "列分隔", "code": " & "},
            {"display": "行分隔", "code": r" \\"},
            {"display": "小矩阵", "code": self.small_matrix_code()}
        ]
        return self.create_button_grid(symbols, columns=4)

    def matrix_code(self, env_type):
        """生成矩阵环境代码"""
        return (
            f"\\begin{{{env_type}}}\n"
            "  a & b \\\\\n"
            "  c & d \n"
            f"\\end{{{env_type}}}"
        )

    def small_matrix_code(self):
        """生成行内小矩阵代码"""
        return (
            r"\left[\begin{smallmatrix}"
            r"  a & b \\"
            r"  c & d"
            r"\end{smallmatrix}\right]"
        )

    def create_button_grid(self, symbols, columns=6):
        scroll = QScrollArea()
        container = QWidget()
        grid = QGridLayout()
        
        row, col = 0, 0
        for symbol in symbols:
            btn = QPushButton(symbol["display"])
            btn.setToolTip(symbol["code"])
            btn.clicked.connect(lambda _, s=symbol["code"]: self.insertSymbol.emit(s))
            btn.setFixedSize(80, 40)
            grid.addWidget(btn, row, col)
            
            col += 1
            if col >= columns:
                col = 0
                row += 1
        
        container.setLayout(grid)
        scroll.setWidget(container)
        scroll.setWidgetResizable(True)
        return scroll

    def create_greek_tab(self):
        symbols = [
            {"display": "α", "code": r"\alpha"}, {"display": "β", "code": r"\beta"},
            {"display": "γ", "code": r"\gamma"}, {"display": "δ", "code": r"\delta"},
            {"display": "ε", "code": r"\epsilon"}, {"display": "ζ", "code": r"\zeta"},
            {"display": "η", "code": r"\eta"}, {"display": "θ", "code": r"\theta"},
            {"display": "ι", "code": r"\iota"}, {"display": "κ", "code": r"\kappa"},
            {"display": "λ", "code": r"\lambda"}, {"display": "μ", "code": r"\mu"},
            {"display": "ν", "code": r"\nu"}, {"display": "ξ", "code": r"\xi"},
            {"display": "π", "code": r"\pi"}, {"display": "ρ", "code": r"\rho"},
            {"display": "σ", "code": r"\sigma"}, {"display": "τ", "code": r"\tau"},
            {"display": "υ", "code": r"\upsilon"}, {"display": "φ", "code": r"\phi"},
            {"display": "χ", "code": r"\chi"}, {"display": "ψ", "code": r"\psi"},
            {"display": "ω", "code": r"\omega"}
        ]
        return self.create_button_grid(symbols)

    def create_big_greek_tab(self):
        symbols = [
            {"display": "A", "code": r"\Alpha"}, {"display": "B", "code": r"\Beta"},
            {"display": "Γ", "code": r"\Gamma"}, {"display": "Δ", "code": r"\Delta"},
            {"display": "ε", "code": r"\Epsilon"}, {"display": "ζ", "code": r"\Zeta"},
            {"display": "η", "code": r"\Eta"}, {"display": "Θ", "code": r"\Theta"},
            {"display": "ι", "code": r"\Iota"}, {"display": "κ", "code": r"\Kappa"},
            {"display": "λ", "code": r"\Lambda"}, {"display": "μ", "code": r"\Mu"},
            {"display": "ν", "code": r"\Nu"}, {"display": "ξ", "code": r"\Xi"},
            {"display": "∏", "code": r"\Pi"}, {"display": "ρ", "code": r"\Rho"},
            {"display": "∑", "code": r"\Sigma"}, {"display": "T", "code": r"\Tau"},
            {"display": "Υ", "code": r"\Upsilon"}, {"display": "φ", "code": r"\Phi"},
            {"display": "χ", "code": r"\Chi"}, {"display": "Ψ", "code": r"\Psi"},
            {"display": "Ω", "code": r"\Omega"}
        ]
        return self.create_button_grid(symbols)

    def create_operators_tab(self):
        symbols = [
            {"display": "±", "code": r"\pm"}, {"display": "∓", "code": r"\mp"},
            {"display": "×", "code": r"\times"}, {"display": "÷", "code": r"\div"},
            {"display": "√", "code": r"\sqrt{}"}, {"display": "∑", "code": r"\sum"},
            {"display": "∏", "code": r"\prod"}, {"display": "∫", "code": r"\int"},
            {"display": "∮", "code": r"\oint"}, {"display": "∂", "code": r"\partial"},
            {"display": "∞", "code": r"\infty"}, {"display": "∠", "code": r"\angle"},
            {"display": "∇", "code": r"\nabla"}, {"display": "≡", "code": r"\equiv"},
            {"display": "≈", "code": r"\approx"}, {"display": "≠", "code": r"\neq"},
            {"display": "≤", "code": r"\leq"}, {"display": "≥", "code": r"\geq"},
            {"display": "∈", "code": r"\in"}, {"display": "∉", "code": r"\notin"}
        ]
        return self.create_button_grid(symbols)

    def create_arrows_tab(self):
        symbols = [
            {"display": "→", "code": r"\rightarrow"}, {"display": "←", "code": r"\leftarrow"},
            {"display": "↔", "code": r"\leftrightarrow"}, {"display": "⇒", "code": r"\Rightarrow"},
            {"display": "⇐", "code": r"\Leftarrow"}, {"display": "⇔", "code": r"\Leftrightarrow"},
            {"display": "↦", "code": r"\mapsto"}, {"display": "↗", "code": r"\nearrow"},
            {"display": "↘", "code": r"\searrow"}, {"display": "↙", "code": r"\swarrow"},
            {"display": "↖", "code": r"\nwarrow"}, {"display": "↑", "code": r"\uparrow"},
            {"display": "↓", "code": r"\downarrow"}, {"display": "↕", "code": r"\updownarrow"}
        ]
        return self.create_button_grid(symbols)

    def create_sets_tab(self):
        symbols = [
            {"display": "⊂", "code": r"\subset"}, {"display": "⊆", "code": r"\subseteq"},
            {"display": "⊃", "code": r"\supset"}, {"display": "⊇", "code": r"\supseteq"},
            {"display": "∩", "code": r"\cap"}, {"display": "∪", "code": r"\cup"},
            {"display": "∅", "code": r"\emptyset"}, {"display": "∀", "code": r"\forall"},
            {"display": "∃", "code": r"\exists"}, {"display": "¬", "code": r"\neg"},
            {"display": "∴", "code": r"\therefore"}, {"display": "∵", "code": r"\because"},
            {"display": "ℕ", "code": r"\mathbb{N}"}, {"display": "ℤ", "code": r"\mathbb{Z}"},
            {"display": "ℚ", "code": r"\mathbb{Q}"}, {"display": "ℝ", "code": r"\mathbb{R}"},
            {"display": "ℂ", "code": r"\mathbb{C}"}
        ]
        return self.create_button_grid(symbols)

# class MainWindow(QWidget):
#     def __init__(self):
#         super().__init__()
#         self.init_ui()

#     def init_ui(self):
#         layout = QVBoxLayout()

#         # 文本输入框
#         self.text_input = QLineEdit()
#         self.text_input.setPlaceholderText("点击下方符号输入LaTeX命令")
#         layout.addWidget(self.text_input)

#         # 键盘部件
#         self.keyboard = LatexKeyboard()
#         self.keyboard.insertSymbol.connect(self.insert_text)
#         layout.addWidget(self.keyboard)

#         self.setLayout(layout)
#         self.setWindowTitle("LaTeX数学符号输入器")
#         self.show()

#     def insert_text(self, symbol):
#         current_text = self.text_input.text()
#         cursor_pos = self.text_input.cursorPosition()
#         self.text_input.setText(current_text[:cursor_pos] + symbol + current_text[cursor_pos:])
#         self.text_input.setFocus()
#         self.text_input.setCursorPosition(cursor_pos + len(symbol))

# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = MainWindow()
#     sys.exit(app.exec_())